package com.burgeon.backend.service.Impl;

import com.burgeon.backend.Rest.User.GETUserByPhone;
import com.burgeon.backend.Rest.coupon.bos.CreateCouponBos;
import com.burgeon.backend.Rest.coupon.bos.DeleteCouponBos;
import com.burgeon.backend.Rest.coupon.bos.GetUserCouponBos;
import com.burgeon.backend.Rest.coupon.util.CreateIntegral;
import com.burgeon.backend.Rest.coupon.util.FindVipQuery;
import com.burgeon.backend.Rest.coupon.util.FindVipQueryByTags;
import com.burgeon.backend.Rest.coupon.xe.CreateCoupon;
import com.burgeon.backend.Rest.coupon.xe.CreateIntegralAndCoupon;
import com.burgeon.backend.Rest.coupon.xe.DeleteCoupon;
import com.burgeon.backend.Rest.coupon.xe.GetUserCoupon;
import com.burgeon.backend.SHOPBACKEND.entity.couponGift.CouponGiftItem;
import com.burgeon.backend.SHOPBACKEND.service.BackendCouponGiftService;
import com.burgeon.backend.entity.*;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import com.burgeon.backend.service.CouponService;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.ex.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CouponServiceImpl implements CouponService {
    private final static Log logger = LogFactory.getLog(CouponService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;
    @Autowired
    private BackendCouponGiftService backendCouponGiftService;


    @Override
    public synchronized void  PointsAreRedeemedForCoupons(String tid, String phone, String token) throws ErrorDataException {
        if (null==tid||null==phone||null==token){
            throw new ErrorDataException("出现错误,请退出重试");
        }

        //发券扣积分
        String account = accountMapper.GetAccountForToken(token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(new Date());
        Info info = GetInfo(account);
        CouponType couponType = couponMapper.findCouponTypeById(tid);
        String code = create_nonce_str().replace("-", "").trim().substring(0, 12);
        Coupon coupon = new Coupon();
        coupon.setCode(code);
        coupon.setVipCode(phone);
        coupon.setCreation(dateString);
        coupon.setTypeid(tid);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setMoney(couponType.getMoney());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setAccount(account);
        coupon.setToken(token);
        String source = "发券扣积分";
        coupon.setSource(source);
        String inid = null;
        String objid = null;
        if (!"1".equals(couponType.getScene())) {//线上卷不写入系统
            List<String> goods = new ArrayList<>();
            List<String> stores = new ArrayList<>();

            if ("Y".equals(couponType.getRestrictProduct())){
                goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

            }
            if ("Y".equals(couponType.getRestrictStore())){
                stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());

            }

            try {
                if ("BOS".equals(info.getSystem())) {
                    CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                    CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                    inid = createIntegral.getData(phone, couponType.getIntegral());
                   // coupon.setVipIntegral(inid);
                    objid = createCoupon.getData(coupon,goods,stores);

                } else {
                    GETUserByPhone getUserByPhone = new GETUserByPhone(info.getUrl(), info.getAccount(), info.getPassword());
                    User data = getUserByPhone.getData(phone);
                    if (Integer.parseInt(data.getIntegral())<Integer.parseInt(couponType.getIntegral())){
                        throw new ErrorDataException("积分不足,领取失败");
                    }
                    CreateIntegralAndCoupon createIntegralAndCoupon = new CreateIntegralAndCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                    createIntegralAndCoupon.getData(coupon);
                   /* CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                    CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());

                    inid = createIntegral.getData(phone, couponType.getIntegral());
                    //coupon.setVipIntegral(inid);
                    objid = createCoupon.getData(coupon);*/

                }

            } catch (Exception e) {
                logger.error(e.getMessage() + "创建优惠券错误" + inid + ";" + phone);
                logger.error(Arrays.toString(e.getStackTrace()));
                throw new ErrorDataException(e.getMessage());
            }
        }
        coupon.setObjid(objid);
        Integer row = couponMapper.addCoupon(coupon);

        if (row != 1) {
            logger.error("创建优惠券出错" + inid + ";" + phone);
        }

        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (ErrorDataException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<CouponType> showRedeemCoupons(String token) throws ErrorDataException {
        //是积分商城未过期购物券类型
        ArrayList<CouponType> data = new ArrayList<>();
        List<CouponType> list = couponMapper.ConversionCoupon(token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());

        for (CouponType ct : list) {
            if (Integer.parseInt(ct.getDateend()) >= Integer.parseInt(date)) {
                data.add(ct);
            }
        }
        return data;
    }


    @Override
    public void addCoupon(String id, String phone, String account) throws InsertException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        String dateString = sdf.format(now);
        Info info = GetInfo(account);
        CouponType couponType = couponMapper.findCouponTypeById(id);
        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        System.err.println(couponType);
        Coupon coupon = new Coupon();
        coupon.setCode(code);
        coupon.setVipCode(phone);
        coupon.setCreation(dateString);
        coupon.setTypeid(id);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setMoney(couponType.getMoney());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setAccount(account);
        coupon.setToken(info.getToken());

        String source = "发放优惠券";
        coupon.setSource(source);

        String objid = null;
        if (!"1".equals(couponType.getScene())) {//线上卷不写入系统
            List<String> goods = new ArrayList<>();
            List<String> stores = new ArrayList<>();

            if (couponType.getRestrictProduct().equals("Y")){
                goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

            }
            if (couponType.getRestrictStore().equals("Y")){
                stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());

            }
            try {
                if ("BOS".equals(info.getSystem())) {
                    CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                    objid = createCoupon.getData(coupon,goods,stores);
                } else {
                    CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                    coupon.setVipIntegral("0");
                    objid = createCoupon.getData(coupon);
                }
            } catch (Exception e) {
                logger.error(e.getMessage() + "创建优惠券错误" + ";" + phone);
                throw new InsertException("创建失败");
            }
        }

        coupon.setObjid(objid);
        couponMapper.addCoupon(coupon);

        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (ErrorDataException e) {
            System.err.println("未绑定公众号");
            throw new InsertException("未绑定公众号,取消发送模板消息");
        }

    }

    @Override
    public List<Coupon> FindUserCoupon(String phone, String token) throws ErrorDataException {
       /* Info info = GetInfoByToken(token);
        ArrayList<Coupon> data;
        try {
            if ("BOS".equals(info.getSystem())) {
                GetUserCouponBos getUserCoupon = new GetUserCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                data = getUserCoupon.getData(phone);
            } else {
                GetUserCoupon getUserCoupon = new GetUserCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                data = getUserCoupon.getData(phone);
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "优惠券数据错误");
            throw new ErrorDataException("优惠券数据错误");
        }*/

        List<Coupon> data = couponMapper.findCouponByPhone(phone, token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        int now = Integer.parseInt(sdf.format(new Date()));
        for (Coupon coupon:data){
            coupon.setVerifyed(!"N".equalsIgnoreCase(coupon.getUse())?"否":"是");
            coupon.setType("VOU5".equals(coupon.getType())?"优惠券":"折扣券");
            if (now<=Integer.parseInt(coupon.getDateend())){
                coupon.setValided("是");
            }else {
                coupon.setValided("否");
            }
        }
        return data;
    }

    @Override
    public List<Coupon> OldFindUserCoupon(String phone, String token) {
         Info info = GetInfoByToken(token);
        ArrayList<Coupon> data;
        try {
            if ("BOS".equals(info.getSystem())) {
                GetUserCouponBos getUserCoupon = new GetUserCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                data = getUserCoupon.getData(phone);
            } else {
                GetUserCoupon getUserCoupon = new GetUserCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                data = getUserCoupon.getData(phone);
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "优惠券数据错误");
            throw new ErrorDataException("优惠券数据错误");
        }
        return data;
    }


    @Override
    public void batchAddThisCoupon(String id,ArrayList<String> data, String flag,String account) throws ErrorDataException {
        Info info = GetInfo(account);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateString = sdf.format(now);

        if (flag != "" && flag != null && flag.equals("T") ){
            for (String phone: data) {
                backendCouponGiftService.createCoupon(id,phone,account);
            }
        }else{
            CouponType couponType = couponMapper.findCouponTypeById(id);

            Coupon coupon = new Coupon();
            coupon.setTypeid(id);
            coupon.setCreation(dateString);
            coupon.setType(couponType.getType());
            coupon.setDiscount(couponType.getDiscount());
            coupon.setDatebeg(couponType.getDatebeg());
            coupon.setDateend(couponType.getDateend());
            coupon.setIntegral(couponType.getIntegral());
            coupon.setOriginal(couponType.getOriginal());
            coupon.setMoney(couponType.getMoney());
            coupon.setAccount(account);
            coupon.setToken(info.getToken());
            coupon.setScene(couponType.getScene());

            runSend(account, dateString, info, data, coupon,couponType);
        }

    }

    private void runSend(String account, String dateString, Info info, ArrayList<String> data, Coupon coupon,CouponType couponType) throws ErrorDataException {
        if ("BOS".equals(info.getSystem())) {

            CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");
                    throw new ErrorDataException("批量执行数据异常");
                }
            }

            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : data) {
                        try {
                            BactchRunBos(coupon, phone, createCoupon,couponType);
                            def = 0;
                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            // couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        } else {
            //CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");

                    throw new ErrorDataException("批量执行数据异常");
                }
            }

            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : data) {
                        try {
                            BactchRun(coupon, phone, createCoupon);
                            def = 0;
                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            //couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        }
    }

    @Override
    public HashMap getCoupon(String start, String account) throws LoadingException {

        // Info info = GetInfo(account);
        HashMap data = new HashMap();
        List<Coupon> couponList = couponMapper.getCoupon(account, Integer.parseInt(start));
        for (Coupon coupon : couponList){

            if (coupon.getScene()==null){

                coupon.setScene("3");
            }
            if (coupon.getUse()==null){
                coupon.setUse("N");
            }
            System.err.println(coupon.getScene());
        }
        data.put("data", couponList);
        data.put("count", couponMapper.findCouponCount(account));

      /*  try {
            if ("BOS".equals(info.getSystem())) {
                GetCouponALLBos getCouponALL = new GetCouponALLBos(info.getUrl(), info.getAccount(), info.getPassword());
                data = getCouponALL.getData(Integer.parseInt(start));
            } else {
                GetCouponALL getCouponALL = new GetCouponALL(info.getUrl(), info.getAccount(), info.getPassword());
                data = getCouponALL.getData(Integer.parseInt(start));
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "获取购物券出错");
            throw new LoadingException("数据出错");
        }*/

        return data;
    }


    @Override
    public void delCoupon(String id, String account) throws DeleteException {
        String objid = couponMapper.FindCouponById(id).getObjid();

        if (objid != null) {
            Info info = GetInfo(account);
            try {
                if ("BOS".equals(info.getSystem())) {
                    DeleteCouponBos deleteCoupon = new DeleteCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                    deleteCoupon.getData(objid);
                } else {
                    DeleteCoupon deleteCoupon = new DeleteCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                    deleteCoupon.getData(objid);
                }
            } catch (Exception e) {
                logger.error("删除购物券错误");
                throw new DeleteException("删除数据出现错误");
            }
        }

        couponMapper.delCoupon(id);

    }

    @Override
    @Transactional
    public void addCouponType(CouponType couponType, String account) throws InsertException {
        Info info = GetInfo(account);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(now);
        couponType.setAccount(account);
        couponType.setToken(info.getToken());
        couponType.setCreation(dateString);
        Integer row;
        try {
            row = couponMapper.addCouponType(couponType);
            if ("Y".equals(couponType.getRestrictBrand())) {
                for (String id : couponType.getBrandList()) {
                    CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                    couponTypeRestrict.setCouponTypeId(couponType.getId());
                    couponTypeRestrict.setRestrictId(id);
                    couponRestrictMapper.createCouponTypeRestrictBrand(couponTypeRestrict);
                }
            }
            if ("Y".equals(couponType.getRestrictClass())) {
                for (String id : couponType.getClassList()) {
                    CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                    couponTypeRestrict.setCouponTypeId(couponType.getId());
                    couponTypeRestrict.setRestrictId(id);
                    couponRestrictMapper.createCouponTypeRestrictClass(couponTypeRestrict);
                }
            }
            if ("Y".equals(couponType.getRestrictProduct())) {
                for (String code : couponType.getCodeList()) {
                    CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                    couponTypeRestrict.setCouponTypeId(couponType.getId());
                    couponTypeRestrict.setName(code);
                    couponRestrictMapper.createCouponTypeRestrictProduct(couponTypeRestrict);
                }
            }
            if ("Y".equals(couponType.getRestrictStore())) {
                for (String code : couponType.getStoreList()) {
                    CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                    couponTypeRestrict.setCouponTypeId(couponType.getId());
                    couponTypeRestrict.setName(code);
                    couponRestrictMapper.createCouponTypeRestrictStore(couponTypeRestrict);
                }
            }



        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            logger.error("新增数据出现错误");
            throw new InsertException("新增数据出现错误");
        }
        if (row != 1) {
            logger.error("新增数据出现错误");
            throw new InsertException("新增数据出现错误");
        }
    }

    @Override
    @Transactional
    public void modCouponType(CouponType couponType) throws UpDataException {
        System.err.println(couponType);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(now);
        couponType.setCreation(dateString);
        couponRestrictMapper.delCouponTypeRestrictBrand(couponType.getId());
        couponRestrictMapper.delCouponTypeRestrictClass(couponType.getId());
        couponRestrictMapper.delCouponTypeRestrictProduct(couponType.getId());
        couponRestrictMapper.delCouponTypeRestrictStore(couponType.getId());
        if ("Y".equals(couponType.getRestrictBrand())) {
            for (String id : couponType.getBrandList()) {
                CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                couponTypeRestrict.setCouponTypeId(couponType.getId());
                couponTypeRestrict.setRestrictId(id);
                couponRestrictMapper.createCouponTypeRestrictBrand(couponTypeRestrict);
            }
        }
        if ("Y".equals(couponType.getRestrictClass())) {
            for (String id : couponType.getClassList()) {
                CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                couponTypeRestrict.setCouponTypeId(couponType.getId());
                couponTypeRestrict.setRestrictId(id);
                couponRestrictMapper.createCouponTypeRestrictClass(couponTypeRestrict);
            }
        }
        if ("Y".equals(couponType.getRestrictProduct())) {
            for (String code : couponType.getCodeList()) {
                CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                couponTypeRestrict.setCouponTypeId(couponType.getId());
                couponTypeRestrict.setName(code);
                couponRestrictMapper.createCouponTypeRestrictProduct(couponTypeRestrict);
            }
        }
        if ("Y".equals(couponType.getRestrictStore())) {
            for (String code : couponType.getStoreList()) {
                CouponTypeRestrict couponTypeRestrict = new CouponTypeRestrict();
                couponTypeRestrict.setCouponTypeId(couponType.getId());
                couponTypeRestrict.setName(code);
                couponRestrictMapper.createCouponTypeRestrictStore(couponTypeRestrict);
            }
        }
        Integer row = couponMapper.modCouponType(couponType);
        if (row != 1) {
            logger.error("修改数据出现错误");
            throw new UpDataException("修改数据出现错误");
        }
    }

    @Override
    @Transactional
    public void delCouponType(String id) throws DeleteException {
        Integer row = couponMapper.delCouponType(id);
        couponRestrictMapper.delCouponTypeRestrictBrand(id);
        couponRestrictMapper.delCouponTypeRestrictClass(id);
        couponRestrictMapper.delCouponTypeRestrictProduct(id);
        couponRestrictMapper.delCouponTypeRestrictStore(id);
        if (row != 1) {
            logger.error("删除数据出现错误");
            throw new DeleteException("删除数据出现错误");
        }
    }

    @Override
    public List<CouponType> getCouponType(String account) throws LoadingException {
        List<CouponType> data;
        try {
            data = couponMapper.getCouponType(account);
            for (CouponType couponType : data) {
                couponType.setBrandList(couponRestrictMapper.getCouponTypeRestrictBrand(couponType.getId()));
                couponType.setClassList(couponRestrictMapper.getCouponTypeRestrictClass(couponType.getId()));
                couponType.setCodeList(couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId()));
                couponType.setStoreList(couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId()));

            }
        } catch (Exception e) {
            logger.error("获取优惠券类型错误:" + e.getMessage());
            throw new LoadingException("获取优惠券类型错误");
        }
        return data;
    }

    @Override
    public CouponType findCouponType(String id) throws LoadingException {
        return couponMapper.findCouponTypeById(id);
    }

    @Override
    public List<String> Query(VipQuery query, String account) throws ErrorDataException {
        Info info = GetInfo(account);

        FindVipQuery findVipQuery = new FindVipQuery(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return findVipQuery.getData(query);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            throw new ErrorDataException("获取数据失败,请稍后重试");
        }

    }

    @Override
    public List<String> QueryTags(VipAttrib query, String account) throws ErrorDataException {
        Info info = GetInfo(account);
        FindVipQueryByTags findVipQuery = new FindVipQueryByTags(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return findVipQuery.getData(query);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            throw new ErrorDataException("获取数据失败,请稍后重试");
        }

    }

    /**
     * 批量添加
     *
     * @param id
     * @param query
     * @param account
     * @throws ErrorDataException
     */

    @Override
    public void batchAddCoupon(String id, VipQuery query, String account) throws ErrorDataException {

        Info info = GetInfo(account);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateString = sdf.format(now);
        ArrayList<String> data;
        FindVipQuery findVipQuery = new FindVipQuery(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            logger.error("批量添加优惠券获取列表出错:" + e.getMessage());
            throw new ErrorDataException("查询数据错误");
        }

        CouponType couponType = couponMapper.findCouponTypeById(id);
        Coupon coupon = new Coupon();
        coupon.setCreation(dateString);
        coupon.setTypeid(id);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setMoney(couponType.getMoney());
        coupon.setAccount(account);
        coupon.setToken(info.getToken());
        String source = "智能营销";
        coupon.setSource(source);

        if ("BOS".equals(info.getSystem())) {

            CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");
                    throw new ErrorDataException("批量执行数据异常");

                }
            }

            ArrayList<String> finalData = data;
            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : finalData) {
                        try {
                            BactchRunBos(coupon, phone, createCoupon,couponType);
                            def = 0;

                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                e.printStackTrace();
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        } else {

            //CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");

                    throw new ErrorDataException("批量执行数据异常");
                }
            }

            ArrayList<String> finalData = data;
            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : finalData) {
                        try {
                            BactchRun(coupon, phone, createCoupon);
                            def = 0;
                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        }
    }

    @Override
    public void batchAddCouponByTags(String id, VipAttrib query, String account) throws ErrorDataException {

        Info info = GetInfo(account);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateString = sdf.format(now);
        ArrayList<String> data;
        FindVipQueryByTags findVipQuery = new FindVipQueryByTags(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            logger.error("tags批量添加优惠券获取列表出错:" + e.getMessage());

            throw new ErrorDataException("查询数据错误");
        }

        CouponType couponType = couponMapper.findCouponTypeById(id);

        Coupon coupon = new Coupon();
        coupon.setTypeid(id);
        coupon.setCreation(dateString);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setMoney(couponType.getMoney());
        coupon.setAccount(account);
        coupon.setToken(info.getToken());
        String source = "智能营销";
        coupon.setSource(source);


        if ("BOS".equals(info.getSystem())) {

            CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");
                    throw new ErrorDataException("批量执行数据异常");
                }
            }

            ArrayList<String> finalData = data;
            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : finalData) {
                        try {
                            BactchRunBos(coupon, phone, createCoupon,couponType);
                            def = 0;
                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        } else {
            //  CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
            Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", account);
            if (row != 1) {
                row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", account);
                if (row != 1) {
                    logger.error("批量执行数据异常:");

                    throw new ErrorDataException("批量执行数据异常");
                }
            }

            ArrayList<String> finalData = data;
            Thread thread = new Thread() {
                int def = 0;

                public void run() {
                    for (String phone : finalData) {
                        try {
                            BactchRun(coupon, phone, createCoupon);
                            def = 0;
                        } catch (Exception e) {

                            def += 1;
                            couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                            coupon.setState("失败");
                            couponMapper.addCoupon(coupon);
                            System.err.println("出错");
                            if (def >= 10) {
                                couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                return;
                            }
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    String dateString = sdf.format(now);
                    couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                }
            };
            thread.start();
        }
    }

    @Override
    public BatchCouponState GetBatchState(String account) {
        return couponMapper.GetBatchCouponState(account);
    }

    private synchronized void BactchRun(Coupon coupon, String phone, CreateCoupon createCoupon) throws Exception {

        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        coupon.setVipCode(phone);
        coupon.setCode(code);
        coupon.setCheckno(code);
        coupon.setState("成功");
        String objid = null;

        String source = "智能营销";
        coupon.setSource(source);

        if (!"1".equals(coupon.getScene())) {
            objid = createCoupon.getData(coupon);
        }
        coupon.setObjid(objid);
        couponMapper.addCoupon(coupon);
        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (Exception e) {
            logger.error("消息发送失败:" + e.getMessage());
            System.err.println("消息发送失败");
        }
        couponMapper.UpdataBatchCouponState(1, -1, 0, coupon.getAccount());

    }

    private synchronized void BactchRunBos(Coupon coupon, String phone, CreateCouponBos createCoupon,CouponType couponType) throws Exception {

        List<String> goods = new ArrayList<>();
        List<String> stores = new ArrayList<>();

        if (couponType.getRestrictProduct().equals("Y")){
            goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

        }
        if (couponType.getRestrictStore().equals("Y")){
            stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());

        }
        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        coupon.setVipCode(phone);
        coupon.setCode(code);
        coupon.setCheckno(code);
        coupon.setVipCode(phone);
        coupon.setState("成功");

        String source = "智能营销";
        coupon.setSource(source);

        String objid = null;
        if (!"1".equals(coupon.getScene())) {

            objid = createCoupon.getData(coupon,goods,stores);

        }
        coupon.setObjid(objid);
        couponMapper.addCoupon(coupon);

        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (Exception e) {
            logger.error("消息发送失败:" + e.getMessage());

        }
        couponMapper.UpdataBatchCouponState(1, -1, 0, coupon.getAccount());
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }

    private Info GetInfo(String account) {
        return accountMapper.GetAccData(account);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }


}
